#!/bin/bash
# this script comes with no warranty, support and is used at own risk.
# it might destroy your data, so make sure you have backups.
# call script with --help for help.

# execute the given command, inspect return code, and abort script on detected failure
function docmd {
	$*
	sig=$?
	if [ "$sig" != "0" ]; then
		echo "got error signal $sig when executing the following command:"
		echo "$*"
		echo aborting ...
		exit 1
	fi
}

# determine if a given tool exists and is within path, otherwise abort script
function testcmd {
	which "$1" > /dev/null
	ret=$?
	if [ "$ret" != "0" ]; then
		$1
		echo "error, some required tools not found, aborting ..."
		exit 1
	fi
}

# determine if a directory exists, otherwise abort script
function testdir {
	if [ ! -d "$1" ]; then
		ls "$1"
		echo "error, required directory not found, aborting ..."
		exit 1
	fi
}

# the given variable must not be empty, otherwise abort script
function testnotempty {
	if [  "$2" == "" ]; then
		echo "error, script variable '\$$1' was empty, but should be, aborting ..."
		exit 1
	fi
}

# doh
function confirmme {
	echo "press enter when done ..."
	read
}

# ask user for positive confirmation, otherwise abort
function askme {
	echo -n "do yo really want to continue? (yes/no) "
	read a
	if [ "$a" != "yes" ]; then
		echo
		echo "aborting at your own wish."
		exit 1
	fi
}

# print help when no argument or just --help was given
if [ "$1" == "" -o "$1" == "--help" ]; then
	echo "gpn-update.sh: error, missing arguments"
	echo
	echo "Usage: gpn-update.sh COMMAND [CONFGENTICSPATH SHAREDLIBPATH WEBAPPSPATH]"
	echo
	echo "COMMAND: one of \"update\" (update an existing installation) or \"check\" (looking for updates for an existing installation), or --help"
	echo "PATHs (optional): if you don't pass any path arguments, we will try to find and guess them using the locate command."
	echo
	echo "Examples:"
	echo "./gpn-update.sh update"
	echo "./gpn-update.sh update /opt/tomcat/conf/gentics /opt/tomcat/shared/lib /opt/tomcat/webapps"
	echo
	echo "this script:"
	echo "- requires some commands to be available within path (wget, unzip, ...). it will abort if they are not available."
	echo "- downloads the new Gentics Portal.Node update using a https connection and the license key in the given CONFGENTICSPATH"
	echo "- extracts the update to the tmp dir"
	echo "- is interactive and requires your confirmation"
	echo "- deletes the old jars from tomcat shared lib directory. other jars stored their will stay untouched"
	echo "- deletes the Portal.Node webapp (extracted and the .war)"
	echo "- moves the new jars and the new webapp (.war only) to the given directories"
	exit 1
fi

echo
echo "WARNING WARNING WARNING"
echo "this script comes with no warranty, support and is used at own risk."
echo "it might destroy your data, so make sure you have backups."
confirmme

# store arguemnts to globals
COMMAND=$1
CONF=$2
SHARED=$3
WEBAPPS=$4

# some statics
BUILDURL="https://secure.gentics.com/update/GPN/4/build/"
DLURL="https://secure.gentics.com/Portal.Node.License/license/downloads"
FILENAMEURL="https://secure.gentics.com/update/GPN/4/filename/"
TMP="/var/tmp"

# look for required tools
testcmd curl
testcmd unzip
testcmd cat
testcmd grep
testcmd sed
testcmd head
testcmd wget
testdir $TMP

# no paths given, autodetect them
if [ "$4" == "" ]; then
	echo "trying to guess where your installation is ..."
	testcmd locate
	gpn=`locate webapps/Portal.Node.war`

	# default value for confirm question
	q=n
	
	# iterate found paths to webapp, for further inspection
	for p in $gpn; do
		cathome=`echo "$p" | sed 's/\/webapps.*//'`
		echo "inspecting $cathome"

		CONF="$cathome/conf/gentics"
		SHARED="$cathome/shared/lib"
		WEBAPPS="$cathome/webapps"

		# do the required directories exist, next to the found webapp?
		if [ -d $CONF -a -d $SHARED -a -d $WEBAPPS ]; then
			echo
			echo "sucess, the following paths have been guessed:"
			echo CONFGENTICSPATH	$CONF
			echo SHAREDLIBPATH	$SHARED
			echo WEBAPPSPATH	$WEBAPPS
			echo -n "do you want to use them? (y/n) "
			read q
			if [ "$q" == "y" ]; then
				echo
				break
			fi
		fi

	done

	# no satisfying results found
	if [ ! -d "$CONF" -o ! -d "$SHARED" -o ! -d "$WEBAPPS" -o $q != "y" ]; then
		echo "sorry, we couldn't guess the installation paths, you will need to pass the arguments manually, or update your locatedb."
		echo "see --help for details"
		echo
		exit 1
	fi

fi

# validate given or detected dirs
testdir $SHARED
testdir $WEBAPPS

# determine some information required for update
localbuild=`cat $WEBAPPS/Portal.Node/META-INF/VERSION.txt  | grep ^build | sed 's/[^0-9]//g'`
testnotempty $localbuild localbuild
remotebuild=`curl -s -k $BUILDURL`
testnotempty $remotebuild remotebuild
filename=`curl -s -k $FILENAMEURL`
testnotempty $filename filename
license=`cat $CONF/license.key | head -n 1 | sed "s/[^0-9A-F\-]//g"`
testnotempty $license license

# print some info about the system to the user
echo "your build is \"$localbuild\""
echo "latest build is \"$remotebuild\""
echo "your license key is \"$license\""

# updates available
if [ "$localbuild" != "$remotebuild" ]; then
	echo "updates are available for your installation."
	echo

	# just check, do nothing else
	if [ "$COMMAND" == "check" ]; then
		echo "run script with argument 'update' to install update."
		exit 2
	fi

	echo "read http://www.gentics.com/changelog/pn/ now, and take care about manual and important changes ..."
	confirmme

	echo "cleaning up tmp dir $TMP ..."
	docmd rm -f "$TMP/$filename"
	docmd rm -Rf $TMP/portal-package
	echo

	echo "downloading to $TMP/$filename ..."
	docmd wget -q -O $TMP/$filename "$DLURL/$filename?sn=$license&filename=$filename"
	echo

	echo "you need to stop tomcat now. open another shell or suspend this script ..."
	confirmme

	echo "we are about to replace all old $SHARED/*.jar, $WEBAPPS/Portal.Node.war and remove $WEBAPPS/Portal.Node ..."
	askme

	echo starting updating ...
	echo

	echo "extracting new build to $TMP/portal-package/ ..."
	docmd cd $TMP
	docmd unzip -q $filename
	docmd cd $TMP/portal-package/portal
	docmd mkdir gentics-portalnode-sharedlibs
	docmd cd gentics-portalnode-sharedlibs
	docmd unzip -q ../gentics-portalnode-sharedlibs.zip
	docmd cd $SHARED
	echo

	echo "looking for old .jars to delete them (Portal.Node/META-INF/SHAREDLIB_MD5.txt)..."
	jars=`cat $WEBAPPS/Portal.Node/META-INF/SHAREDLIB_MD5.txt | sed "s/^.* //"`
	testnotempty $jars jars
	echo

	echo "removing old build from $SHARED ..."
	# TODO validate checksums
	docmd rm -f $jars
	echo

	echo "moving new build to $SHARED ..."
	docmd mv $TMP/portal-package/portal/gentics-portalnode-sharedlibs/* .
	echo

	echo "removing old build from $WEBAPPS ..."
	docmd rm -Rf $WEBAPPS/Portal.Node*
	echo

	echo "moving new build to $WEBAPPS ..."
	docmd mv $TMP/portal-package/portal/Portal.Node.war $WEBAPPS
	echo

	echo "you need to restart tomcat now ..."
	confirmme
	echo "gratulation! it's done, bye bye!"
else
	echo "no updates available, your installation is uptodate ..."
	exit 0
fi
